package com.qf.controller;

import com.github.pagehelper.PageInfo;
import com.qf.entity.Annunciate;
import com.qf.entity.Word;
import com.qf.enums.OAExceptionEnum;
import com.qf.service.WordService;
import com.qf.utils.*;
import com.qf.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 2019/12/14
 * qjh
 * springboot_oa_five
 * 面向对象面向君 不负代码不负卿
 */

@Controller
@Slf4j
public class WordController {

    private final String PIC_DIR = "images";
    private final String APK_DIR = "apks";

    @Value("${file.poi.ty}")
    private String ty;

    @Autowired
    private WordService wordService;

    @Autowired
    private UploadUtil uploadUtil;

    //分页查询所有信息
    @RequestMapping("/resource/wendang/demo1/list")
    public String findWordList(@RequestParam(defaultValue = "1")Integer page, @RequestParam(defaultValue = "")String wordName, ModelMap modelMap){
        PageInfo<Word> allWord = wordService.findAllWord(page, wordName);
        modelMap.addAttribute("allWord",allWord);
        modelMap.addAttribute("wordName",wordName);
        return "/resource/wendang/demo1/list";
    }

    @RequestMapping("/bathcaozuo")
    public void bathCaoZuo(int[] arr, String method, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        if(method.equals("delete")){
            PrintWriter writer = response.getWriter();
            if(arr==null){
                writer.print("<script>alert('请选择！');location.href='/resource/wendang/demo1/list'</script>");
                return;
            }

            Integer integer = wordService.bathDelete(arr);
            if(integer>0){
                writer.print("<script>alert('删除成功！');location.href='/resource/wendang/demo1/list'</script>");
            }else{
                writer.print("<script>alert('删除失败！不能删除！');location.href='/resource/wendang/demo1/list'</script>");
            }
        }else if(method.equals("daochu")){

            //导出数据
            //1.查询被选中的数据信息
            List<Word> words = wordService.bathDaochu(arr);
            //2.导出数据
            WendangUtils.createFirst("用户信息");
            WendangUtils.createOthers(words);
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
            String s = format.format(new Date());
            response.setContentType("application/x-download");
            String fileName=s+".xls";
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            ServletOutputStream outputStream = response.getOutputStream();
            WendangUtils.export(outputStream);

//                ExcelUtils.export(new FileOutputStream("f://"+(format.format(new Date()))+".xls"));
//            writer.print("<script>alert('导出成功');location.href='/resource/tonggao/demo1/list'</script>");

        }
    }


    //跳转文件夹添加页面
    @RequestMapping("/tiaozhuangwenjianjia")
    public String addflter(){
        return "/resource/wendang/demo1/add";
    }

    //添加文件夹
    @RequestMapping("/wordaddwenjianjia")
    public void wordAddWenJianJia(Word word,HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        Integer integer = wordService.addwenjianjia(word);
        if(integer>0){
            writer.print("<script>alert('添加成功！');location.href='/resource/wendang/demo1/list'</script>");
        }else{
            writer.print("<script>alert('添加失败！');location.href='/resource/wendang/demo1/list'</script>");
        }
    }

    //跳转文件添加页面
    @RequestMapping("/tiaozhuangwenjian")
    public String addWenJian(ModelMap modelMap){
        List<Word> allWenJianJia = wordService.findAllWenJianJia();
        modelMap.addAttribute("allWenJianJia", allWenJianJia);
        return "/resource/wendang/demo1/add1";
    }

    //添加文件
    @RequestMapping("/wordaddwenjian")
    public void wordAddWenJian(Word word,HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        Integer integer = wordService.addwenjian(word);
        if(integer>0){
            writer.print("<script>alert('添加成功！');location.href='/resource/wendang/demo1/list'</script>");
        }else{
            writer.print("<script>alert('添加失败！');location.href='/resource/wendang/demo1/list'</script>");
        }
    }

    //ajax查询文件
    @RequestMapping("/wendang/demo1/wordName")
    @ResponseBody
    public List<Word> findSecondWord(Integer wordSupId,Integer wordId){
        List<Word> words = wordService.findSecondWord(wordId);
        if(words.size()==0){
            return null;
        }
        return words;
    }

    //文件上传
    @RequestMapping("/workfile")
    @ResponseBody
    public ResultVO apk(MultipartFile file) throws IOException {
        //1. 校验是否非空.
        if(file == null){
            log.info("【上传APK文件】 文件上传项为空!!");
            return R.error(OAExceptionEnum.APK_EXISTS);
        }
        //2. 校验大小.
        if(file.getSize() > 52428880){
            log.info("【上传APK文件】 文件上传项多大. file = {}",file);
            return R.error(OAExceptionEnum.APK_TOO_BIG);
        }

        //3. 校验类型.
        boolean flag = false;

        String[] typesArray = ty.split(",");
        for (String type : typesArray) {
            if(StringUtils.endsWithIgnoreCase(file.getOriginalFilename(),type)){
                // 类型匹配.
                flag = true;
                break;
            }
        }

        if(!flag){
            // 记录日志,返回结果
            log.info("【上传APK文件】 文件上传项类型不正确. fileName = {}",file.getOriginalFilename());
            return R.error(OAExceptionEnum.APK_TYPE_ERROR);
        }

//        //3. 校验类型.
//        if(!StringUtils.endsWithIgnoreCase(file.getOriginalFilename(),APK_TYPE_NAME)){
//            log.info("【上传APK文件】 文件上传项类型不正确. fileName = {}",file.getOriginalFilename());
//            return R.error(AppEnum.APK_TYPE_ERROR);
//        }

        //4. 起个新名字.
        String apkName = RandomUtil.random();

        //5. 保存到OSS上.
        String src = uploadUtil.uploadPic(APK_DIR + "/" + apkName, file.getInputStream());

        //6. 响应.
        Map<String,String> data = new HashMap<>();
        data.put("src",src);
        return R.ok(data);
    }
}

